var $ = require('webpack-zepto');
var config = require('./config.js');
var util = require('./util.js');

function Auth(){

    this.hasToken = function(appId){
        var token = util.storage().get(appId);
        if(!token){
            token = util.getUrlParam('utoken');
            if(!token){
                return false;
            }else{
                if(!validateToken(token,appId)){
                    return false;
                }else{
                    util.storage().put(appId,token);
                }
            }
        }else{
            if(!validateToken(token,appId)){
                return false;
            }
        }
        return true;
    };

    this.login = function(appId){
        var isLogin = util.getUrlParam('login');
        if('yes' == isLogin){
            return;
        }
        var currentPage = encodeURI(window.location.href),
            loginPath = config.path('wechat/login',['?appId=' + appId,'&returnUrl=' + currentPage]);
        window.location.href = loginPath;
    };

    this.isLogin = function(appId){
        if(!this.hasToken(appId)){
            util.storage().remove(appId);
            this.login(appId);
            return false;
        }
        return true;
    };

    function validateToken(token,appId){
        var result = false;
        $.ajax({
            url : config.path('duolu/user',['?appId=' + appId,'&uToken=' + token , '&validToken']),
            type : 'get',
            async : false,
            success : function(resp){
                if(resp.status == 200){
                    result = true;
                }
            }
        });

        return result;
    };
};

module.exports = new Auth();